<?php

namespace app\admin\model;
use think\Model;
use fast\Auth;

class Mcode extends Model
{
    protected $updateTime = false;
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $table = "fa_mcode";

    public static $tableName = "fa_mcode";

    const TYPE_ORDER_TYPE = 0;
    const TYPE_ORDER_TYPE_1 = 1;
    const TYPE_ORDER_TYPE_2 = 2;
    const TYPE_ORDER_TYPE_3 = 3;
    const TYPE_ORDER_TYPE_4 = 4;
    
    protected static $CODE_PREFIX = [
        "PCM",//pc领料单
        "CKKC",//盘点单
        "MOUT",//mes领料出库
        "MIN", //mes产品入库
        "ZDB" //质检放行 调拨单
    ];

    /**
     * 获取单号
     * @param $type
     * @return false|string
     */
    public static function getCode($type = self::TYPE_ORDER_TYPE)
    {
        $prefix = self::getPrefix($type);
        //$admin_id = Auth::instance()->id;
        $mcode_str = $prefix . date('Ymd', time());

        $last = self::where(['type' => $type])
            ->where('mcode', 'like', $mcode_str . '%')
            ->order('id', 'desc')
            ->find();

        if (!$last) {
            //今天找不到，则新增
            $mcode_str = $mcode_str . '0001';
            $data = [
                'mcode' => $mcode_str,
                //'admin_id' => $admin_id,
                'createtime' => time(),
                'type' => $type
            ];
            self::insert($data);
            return $mcode_str;
        } else {
            //新增
            $num = substr($last->mcode, -4) + 1;
            $num = $mcode_str . sprintf("%04d", $num);
            $data = [
                'mcode' => $num,
                //'admin_id' => $admin_id,
                'createtime' => time(),
                'type' => $type
            ];
            self::insert($data);
            return $num;
        }
    }

    /**
     * @param string $code
     * @return static
     */
    public static function setStatus(string $code)
    {
        return self::update(['status' => 1], ['mcode' => $code]);
    }

    /**
     * @param integer $type
     * @return string
     */
    protected static function getPrefix(int $type)
    {
        return self::$CODE_PREFIX[$type];
    }
}
